package com.cooper.controllers;

import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.constants.ResourceConstants;
import com.cooper.core.JsonResult;
import com.cooper.domain.UserSession;
import com.cooper.entity.UserInfo;
import com.cooper.security.PasswordGeneration;
import com.cooper.service.core.UserService;
import com.cooper.util.Controllers;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

public class RegisterController {

	@Autowired
	private UserService userService;
	
	@Get
	public String execute(Invocation inv) throws Exception{
		inv.addModel("usePanel", inv.getParameter("usePanel"));
		return "account/register";
	}
	
	@Post
	public Object save(Invocation inv, UserInfo user) throws Exception{
		JsonResult json = new JsonResult();
		if(this.userService.existsUserName(user.getUserName())){
			json.setMessage("用户名{0}已经存在", user.getUserName());
			return json;
		}
		
		if(null != this.userService.existsUserEmail(user.getEmail())){
			json.setMessage("邮件地址{0}已经存在", user.getEmail());
			return json;
		}
		
		String userName = user.getUserName();
		user.setUserPassword(PasswordGeneration.encrypt(user.getUserPassword()));
		user.setCreator(userName);
		user.setModifier(userName);
		
		user.setStatus(ResourceConstants.Status.VALID);
		Long userId = this.userService.addUser(user);
		if(null == userId){
			json.setMessage("register failure, server inner error.");
			return json;
		}
		
		user.setId(userId);
		UserSession userSession = new UserSession();
		userSession.setUserInfo(user);
		Controllers.setUserSession(inv, userSession);
		json.setSuccess(true);
		return json;
	}

}
